import {Interface} from "readline";
import fs from 'fs/promises'
import path from 'path'
import logger from "../tools/logger"

const register_commands: PluginInterface[] = []

async function loadFileModels(filePath: string): Promise<any> {
    try {
        return (await import(filePath)).default
    } catch (err) {
        logger.error('Error load plugin:', err);
        return false
    }
}

async function init() {
    const currentDir = path.join(__dirname, "../plugin")
    const files = await fs.readdir(currentDir)
    for (let file of files) {
        const filePath = path.join(currentDir, file);
        const plugin = await loadFileModels(filePath)
        if (plugin != false) {
            register_commands.push(plugin)
        }
    }
}

interface PluginInterface {
    register: string,
    additional_parameters: string,
    ignore_case: boolean,
    use: (ctx: ctxInterface) => void
}

interface ctxInterface {
    cmd: string,
    title: string[],
    input: string,
    registerPlugins:PluginInterface[]
}

export {
    PluginInterface,
    ctxInterface
}
export default async function (shell: Interface) {
    await init()
    // 监听用户输入
    shell.on('line', (input) => {
        const tmpConfig = {
            // 是否成功触发命令
            isUse: false
        }
        // 清空默认输入的返回值
        process.stdout.write('\x1B[1A\x1B[2K');
        // 处理用户输入的命令
        const title = input.trim().split(" ")[0]
        const ctx: ctxInterface = {
            title: input.trim().split(" "),
            cmd: input.trim(),
            input,
            registerPlugins:register_commands
        }
        for (let cmd of register_commands) {
            if (cmd.register == title) {
                cmd.use(ctx)
                tmpConfig.isUse = true
                break
            }
        }
        if (!tmpConfig.isUse) {
            logger.error(`Unknown command: ${input}`)
        }
        shell.prompt()
    });
}